package com.jeasonzhao.web;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;

public class WebHtmlWriter implements IHtmlWriter
{
    private PageContext pageContext = null;
    private boolean isUsingBodyWriter = false;
    private BodyTagSupport tag = null;
    public WebHtmlWriter(BodyTagSupport tag,PageContext context,boolean isUsingBodyWriter)
    {
        this.pageContext = context;
        this.tag = tag;
        this.isUsingBodyWriter = isUsingBodyWriter;
    }

    public WebHtmlWriter(PageContext context)
    {
        this.pageContext = context;
        this.tag = null;
        this.isUsingBodyWriter = false;
    }

    public void write(CharSequence str)
        throws IOException
    {
        if(str == null || null == this.pageContext)
        {
            return;
        }
        else
        {
            try
            {
                BodyContent body = null == this.tag ? null : this.tag.getBodyContent();
                if(body == null || false == isUsingBodyWriter)
                {
                    this.pageContext.getOut().write(str.toString());
                    this.pageContext.getOut().flush();
                }
                else
                {
                    JspWriter out = body.getEnclosingWriter();
                    out.write(str.toString());
                    out.flush();
                }
            }
            catch(Exception excep)
            {
                excep.printStackTrace();
                //do not handle exceptions at here.
            }
        }

    }

    public void disposeWriter()
    {
    }

}
